<?php

Yii::import('common.models.db.BillModel');

class BackendBillModel extends BillModel
{
	public static function model($className=__CLASS__) {
		return parent::model($className);
	}
	public function attributeLabels()
	{
		return array(
				'created_datetime'=>'Ngày nhập',
				'fee'=>'Tiền cước',
				'description'=>'Nội dung',
				'product_weight'=>'Trọng lượng (gram)',
				'customer_address'=>'Địa chỉ khách hàng',
				'customer_name'=>'Tên khách hàng',
				'type'=>'Hãng CPN',
				'code'=>'Mã Bill',
				'receiver'=>'Người nhận',
				'receiver_address'=>'Địa chỉ người nhận'
		);
	}
	public function beforeSave()
	{
		$this->updated_datetime = new CDbExpression('NOW()');
		if($this->id>0){
			$amBill = Yii::app()->db->createCommand("SELECT count(*) FROM bill WHERE am_bill='{$this->am_bill}' and id<>{$this->id}")->queryScalar();
			if($amBill>0){
				$this->addError("am_bill",Yii::t("main","Mã AM Bill này đã tồn tại. Hãy chọn mã khác"));
				return false;
			}
		}else{
			$amBill = Yii::app()->db->createCommand("SELECT count(*) FROM bill WHERE am_bill='{$this->am_bill}'")->queryScalar();
			if($amBill>0){
				$this->addError("am_bill",Yii::t("main","Mã AM Bill này đã tồn tại. Hãy chọn mã khác"));
				return false;
			}
		}
		
		return parent::beforeSave();
	}
	public function afterSave(){
		if($this->type=='AM' && empty($this->air_bill)){
			$model = self::model()->findByPk($this->id);
			$model->air_bill = $this->id;
			$model->save(false);
		}
		return parent::afterSave();
	}
	public static function getByDate($time){
		$sql = "SELECT *, date(created_datetime) as date
				FROM bill
				WHERE created_datetime >='{$time['from']} 00:00:00' AND created_datetime <='{$time['to']} 23:59:59'
				ORDER BY date DESC
				";
		return Yii::app()->db->createCommand($sql)->queryAll();
	}
	public function search() {
		$criteria = new CDbCriteria;
	
		$criteria->compare('id', $this->id);
		$criteria->compare('code', $this->code, true);
		$criteria->compare('type', $this->type, true);
		$criteria->compare('customer_name', $this->customer_name, true);
		$criteria->compare('customer_address', $this->customer_address, true);
		$criteria->compare('description', $this->description, true);
		$criteria->compare('product_weight', $this->product_weight);
		$criteria->compare('fee', $this->fee, true);
		$criteria->compare('created_datetime', $this->created_datetime, true);
		$criteria->compare('updated_datetime', $this->updated_datetime, true);
		$criteria->compare('am_bill', $this->am_bill, true);
		$criteria->compare('air_bill', $this->air_bill, true);
		$criteria->compare('receiver', $this->receiver, true);
		$criteria->compare('receiver_address', $this->receiver_address, true);
	
		return new CActiveDataProvider($this, array(
				'criteria' => $criteria,
		));
	}
}